package com.qunar.train.mock.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;

public class FileCharsetCheck {

    /**
     * 测试输入字节流是否能够使用指定的字符集解码。
     */
    public static boolean canDecode(InputStream input, Charset charset) throws IOException {
        ReadableByteChannel channel = Channels.newChannel(input);
        CharsetDecoder decoder = charset.newDecoder();

        ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        boolean endOfInput = false;
        while (!endOfInput) {
            int n = channel.read(byteBuffer);
            byteBuffer.flip(); // flip so it can be drained

            endOfInput = (n == -1);
            CoderResult coderResult = decoder.decode(byteBuffer, charBuffer, endOfInput);
            charBuffer.clear();
            if (coderResult == CoderResult.OVERFLOW) {
                while (coderResult == CoderResult.OVERFLOW) {
                    coderResult = decoder.decode(byteBuffer, charBuffer, endOfInput);
                    charBuffer.clear();
                }
            }
            if (coderResult.isError()) {
                return false;
            }
            byteBuffer.compact(); // compact so it can be refilled
        }
        CoderResult coderResult;
        while ((coderResult = decoder.flush(charBuffer)) == CoderResult.OVERFLOW) {
            charBuffer.clear();
        }
        if (coderResult.isError()) {
            return false;
        }

        return true;
    }
}

